package io.gitee.zhangbinhub.acp.boot.exceptions

import io.gitee.zhangbinhub.acp.boot.http.HttpStatus
import io.gitee.zhangbinhub.acp.boot.tools.PackageTools
import org.noear.solon.core.exception.StatusException
import org.noear.solon.exception.SolonException
import org.noear.solon.validation.BeanValidateInfo
import org.noear.solon.validation.ValidatorException

class AcpDefaultWebExceptionHandler : AcpWebExceptionHandler {
    override fun identify(ex: Throwable?): Boolean = true
    override fun handle(ex: Throwable?): ErrorResult = when (ex) {
        is WebException -> {
            PackageTools.buildErrorResult(ex.httpStatus, ex.message)
        }

        is ValidatorException -> {
            val validateMessage = when (val resultData = ex.result.data) {
                is BeanValidateInfo -> {
                    resultData.message
                }

                is List<*> -> {
                    resultData.mapNotNull {
                        try {
                            (it as BeanValidateInfo).message
                        } catch (e: Exception) {
                            null
                        }
                    }.joinToString(separator = ";")
                }

                else -> {
                    ex.message
                }
            }
            PackageTools.buildErrorResult(ex.code, validateMessage)
        }

        is StatusException -> {
            PackageTools.buildErrorResult(ex.code, ex.message)
        }

        is SolonException -> {
            PackageTools.buildErrorResult(HttpStatus.BAD_REQUEST, ex.message)
        }

        else -> {
            PackageTools.buildErrorResult(HttpStatus.INTERNAL_SERVER_ERROR, ex?.message)
        }
    }
}